package com.github.freewu.commons.libs;

import android.content.Context;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ListView;
import com.github.freewu.commons.http.HttpCallBack;
import com.github.freewu.commons.http.HttpUtils;
import com.github.freewu.commons.utils.ToastUtil;
import com.github.freewu.mvp.bean.ServerListBean;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonWriter;
import com.joanzapata.android.QuickAdapter;
import com.lqkj.commons.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 刷新视图
 * Created by free on 16-8-15.
 */
public class RefreshView<T> extends FrameLayout implements AbsListView.OnScrollListener, SwipeRefreshLayout.OnRefreshListener {
    private SwipeRefreshLayout swipeRefreshLayout;

    private ListView mListView;

    private QuickAdapter<T> adapter;

    private Class<T> tclass;

    private View footerView;

    private Handler handler = new Handler();

    private String url = "";

    private int page = 1;

    private int pageSize = 5;

    private boolean hasNext = false;

    private boolean isRequest = false;

    private PageNextIntercept pageNextIntercept;

    private String pageString = "page";
    private String pageSizeString = "pageSize";


    public RefreshView(Context context) {
        super(context);

        init();
    }

    public RefreshView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public RefreshView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.refresh_layout, this);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        mListView = (ListView) findViewById(R.id.listview);

        footerView = View.inflate(getContext(), R.layout.refresh_footer_layout, null);

        mListView.setOnScrollListener(this);
        swipeRefreshLayout.setOnRefreshListener(this);
    }

    /**
     * 设置listivew adapter
     *
     * @param adapter
     */
    public void setAdapter(QuickAdapter<T> adapter) {
        this.adapter = adapter;

        if (mListView != null) {
            mListView.setAdapter(adapter);

            swipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(true);

                    onRefresh();
                }
            });
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            if (mListView.getLastVisiblePosition() == (mListView.getCount() - 1)) {
                //滑动到底部
                if (hasNext && !isRequest) {
                    isRequest = true;

                    page++;

                    //显示加载view
                    footerView.setVisibility(View.VISIBLE);
                    //请求数据
                    requestData(true);

                    mListView.addFooterView(footerView);
                }
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    public String getUrl() {
        return url;
    }

    /**
     * @param baseUrl        基本url 例如http://www.baidu.com/
     * @param params         请求参数 例如 ["usercode","1"]
     * @param pageSizeString pageSize的请求字符串
     * @param pageString     page的请求字符串
     */
    public void setUrl(String baseUrl, Map<String, String> params, String pageSizeString, String pageString) {
        List<String> keys = new ArrayList<>(params.keySet());
        List<String> values = new ArrayList<>(params.values());

        StringBuilder builder = new StringBuilder(baseUrl);

        for (int i = 0; i < params.size(); i++) {
            if (i != 0) {
                builder.append("&")
                        .append(keys.get(i))
                        .append("=")
                        .append(values.get(i));
            } else {
                builder.append("?")
                        .append(keys.get(i))
                        .append("=")
                        .append(values.get(i));
            }
        }

        this.url = builder.toString();

        if (pageSizeString != null) {
            this.pageSizeString = pageSizeString;
        } else {
            this.pageSizeString = "pageSize";
        }
        if (pageString != null) {
            this.pageString = pageString;
        } else {
            this.pageString = "page";
        }
    }

    /**
     * pageSizeString pageSize的请求字符串 默认 "page"
     * pageString page的请求字符串默认 “pageZie”
     *
     * @param baseUrl 基本url 例如http://www.baidu.com/
     * @param params  请求参数 例如 ["usercode","1"]
     */
    public void setUrl(String baseUrl, Map<String, String> params) {
        setUrl(baseUrl, params, "pageSize", "page");
    }

    /**
     * 下拉刷新回调
     */
    @Override
    public void onRefresh() {
        page = 1;

        hasNext = false;

        requestData(false);
    }

    private void requestData(final boolean isAdd) {
        HttpUtils.getInstance().get(getHttpUrl(), new HttpCallBack() {
            @Override
            public void onError(Call call,Exception e,int errorCode) {
                swipeRefreshLayout.setRefreshing(false);
                mListView.removeFooterView(footerView);

                ToastUtil.showShort(getContext(), "网络错误");

                isRequest = false;
            }

            @Override
            public void onSuccess(Call call, String body) {
                JsonParser parser=new JsonParser();
                Gson gson=new Gson();

                JsonObject json = parser.parse(body).getAsJsonObject();

                if (pageNextIntercept != null) {
                    hasNext = pageNextIntercept.hasNext(json);
                }

                ServerListBean<T> serverListBean = gson.fromJson(body, new TypeToken<ServerListBean<T>>() {
                }.getType());

                if (serverListBean.isStatus()) {
                    List<T> data=serverListBean.getData();

                    if (isAdd) {
                        mListView.removeFooterView(footerView);
                        adapter.addAll(data);
                    } else {
                        adapter.replaceAll(data);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                } else {
                    ToastUtil.showShort(getContext(), "数据错误");
                    mListView.removeFooterView(footerView);
                    swipeRefreshLayout.setRefreshing(false);
                }

                isRequest = false;
            }
        });
    }

    /**
     * 得到请求
     *
     * @return
     */
    private String getHttpUrl() {
        StringBuilder builder = new StringBuilder(url);

        builder.append("&")
                .append(pageString)
                .append("=")
                .append(page)
                .append("&")
                .append(pageSizeString)
                .append("=")
                .append(pageSize);

        return builder.toString();
    }

    /**
     * 设置下一页数据判断处理
     *
     * @param pageNextIntercept
     */
    public void setPageNextIntercept(PageNextIntercept pageNextIntercept) {
        this.pageNextIntercept = pageNextIntercept;
    }

    public interface PageNextIntercept {
        boolean hasNext(JsonObject json);
    }

    public void setTclass(Class<T> tclass) {
        this.tclass = tclass;
    }
}
